import React, { Suspense, useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { StyleProvider } from '@ant-design/cssinjs';
import { Spin } from 'antd';
import { ThemeProvider } from './contexts/ThemeContext';
import MainLayout from './components/Layout/MainLayout';
import LoadingScreen from './components/LoadingScreen/LoadingScreen';
import Home from './pages/Home';
import ArticleList from './pages/Articles/ArticleList';
import ArticleDetail from './pages/Articles/ArticleDetail';
import ArticleEditor from './pages/Articles/ArticleEditor';
import Register from './pages/Register';
import Login from './pages/Login';
import ProjectStructure from './components/ProjectStructure/ProjectStructure';
import KnowledgeMap from './pages/KnowledgeMap';
import Profile from './pages/Profile';
import { UserProvider } from './contexts/UserContext';
import './styles/theme.scss';
import './App.css';

// 使用React.lazy实现代码分割
const LazyExamples = React.lazy(() => import('./pages/Examples'));

const App: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // 模拟初始化加载
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 2000);

    return () => clearTimeout(timer);
  }, []);

  return (
    <>
      {isLoading && <LoadingScreen />}
      <ThemeProvider>
        <StyleProvider>
          <UserProvider>
            <Router>
              <Suspense fallback={<LoadingScreen />}>
                <Routes>
                  <Route path="/" element={<MainLayout />}>
                    <Route index element={<Home />} />
                    <Route path="articles" element={<ArticleList />} />
                    <Route path="articles/:id" element={<ArticleDetail />} />
                    <Route path="articles/new" element={<ArticleEditor />} />
                    <Route path="articles/edit/:id" element={<ArticleEditor />} />
                    <Route path="register" element={<Register />} />
                    <Route path="login" element={<Login />} />
                    <Route path="project-structure" element={<ProjectStructure />} />
                    <Route 
                      path="/examples" 
                      element={
                        <Suspense fallback={<div style={{ textAlign: 'center', padding: '50px 0' }}><Spin size="large" /></div>}>
                          <LazyExamples />
                        </Suspense>
                      } 
                    />
                    <Route path="/knowledge-map" element={<KnowledgeMap />} />
                    <Route path="/profile" element={<Profile />} />
                  </Route>
                </Routes>
              </Suspense>
            </Router>
          </UserProvider>
        </StyleProvider>
      </ThemeProvider>
    </>
  );
};

export default App;
